#include "user.h"

#define DQ_PORT GPIOB
#define DQ_PIN	LL_GPIO_PIN_1
#define DQ_AF	GPIO_AF0_TIM14
#define IC_TIM	TIM14
#define IC_CHANNEL	LL_TIM_CHANNEL_CH1
#define IC_POLARITY	LL_TIM_IC_POLARITY_FALLING
#define IC_IRQ	TIM14_IRQn

typedef struct
{

	uint32_t PulseCnt;
	uint32_t Temperature;
}NST1001_CtrlStruct;

static NST1001_CtrlStruct NST1001;

void NST1001_Init(void)
{
	LL_TIM_InitTypeDef TIM_InitStruct;
	LL_TIM_IC_InitTypeDef TIM_IC_InitStruct;
	LL_GPIO_InitTypeDef GPIO_InitStruct;
	LL_TIM_StructInit(&TIM_InitStruct);
	TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV4;
	TIM_InitStruct.Autoreload = 60000;
	LL_TIM_IC_StructInit(&TIM_IC_InitStruct);
	TIM_IC_InitStruct.ICPolarity = IC_POLARITY;
	TIM_IC_InitStruct.ICFilter = LL_TIM_IC_FILTER_FDIV1;
	LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM14);
	LL_TIM_Init(IC_TIM, &TIM_InitStruct);
	LL_TIM_IC_Init(IC_TIM, IC_CHANNEL, &TIM_IC_InitStruct);
	LL_TIM_EnableIT_CC1(IC_TIM);
	HAL_NVIC_SetPriority(IC_IRQ, IRQ_MOST_HIGH_LEVEL, 0);
	NVIC_EnableIRQ(IC_IRQ);
	LL_TIM_EnableCounter(IC_TIM);
	GPIO_InitStruct.Pin = DQ_PIN;
	GPIO_InitStruct.Pull = LL_GPIO_PULL_UP;
	GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE;
	GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_HIGH;
	GPIO_InitStruct.Alternate = DQ_AF;
	LL_GPIO_Init(DQ_PORT, &GPIO_InitStruct);

}

uint32_t NST1001_Read(void)
{
	return NST1001.PulseCnt;
}

void NST1001_Clear(void)
{
	NST1001.PulseCnt = 0;
}

void TIM14_IRQHandler(void)
{
	if (IC_TIM->SR & TIM_SR_CC1IF)
	{
		NST1001.PulseCnt++;
		IC_TIM->DIER = 0x03;
		IC_TIM->CNT = 0;
	}
	else if (IC_TIM->SR & TIM_SR_UIF)
	{
		DBG("%u", NST1001.PulseCnt);
		NST1001.PulseCnt = 0;
		IC_TIM->DIER = TIM_SR_CC1IF;
	}
	IC_TIM->SR = 0;
}
